<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i>
                    {{pageTitle}}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <acc-set-card></acc-set-card>
        <div class="container" :style="{'min-height': containerHeight + 'px'}">
            <vxe-toolbar>
                <template v-slot:buttons>
                    <el-button type="primary" icon="el-icon-folder-add" @click="goAdd">新增</el-button>
                    <el-button type="warning" icon="el-icon-edit" @click="goEdit">修改</el-button>
                    <el-button type="danger" icon="el-icon-delete" @click="delAllSelection">删除</el-button>
                    <el-button type="info" @click="goBkpf">抛转总账</el-button>
                </template>
            </vxe-toolbar>

            <div class="handler-box">
                <el-form label-width="100px" :model="query" ref="searchRuleForm">
                    <el-row>
                        <el-col :sm="20" :md="5">
                            <el-form-item label="单号" prop="billId">
                                <el-input v-model="query.billId" clearable></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :sm="20" :md="5">
                            <el-form-item label="单别名称" prop="orderNoCode">
                                <div @click="showTreeDialogSingle('单别')">
                                    <el-input v-model="query.orderNoCode" placeholder="请输入">
                                        <i slot="suffix" class="el-icon-search"></i>
                                    </el-input>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :sm="20" :md="5">
                            <el-form-item label="总账凭证" prop="vochNum">
                                <el-input v-model="query.vochNum" clearable></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :sm="20" :md="5">
                            <el-form-item label="人员" prop="empName">
                                <div @click="showTreeDialog('人员')">
                                    <el-input v-model="query.empName" placeholder="请输入">
                                        <i slot="suffix" class="el-icon-search"></i>
                                    </el-input>
                                </div>
                            </el-form-item>
                        </el-col>

                        <el-col :sm="20" :md="5">
                            <el-form-item label="部门" prop="deptName">
                                <el-input v-model="query.deptName" disabled></el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :sm="20" :md="5">
                            <el-form-item label="日期" prop="billDate">
                                <el-date-picker
                                    v-model="query.billDate"
                                    type="date"
                                    placeholder="选择日期"
                                    clearable
                                ></el-date-picker>
                            </el-form-item>
                        </el-col>

                        <el-col :sm="20" :md="6" align="center">
                            <el-button
                                type="primary"
                                icon="el-icon-search"
                                @click="submitForm('searchRuleForm')"
                            >搜索</el-button>
                            <el-button type="info" @click="resetForm('searchRuleForm')">重置</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </div>

            <vxe-table
                border
                resizable
                keep-source
                highlight-hover-row
                highlight-hover-column
                ref="xTree"
                row-id="id"
                height="500"
                :loading="loading"
                :radio-config="{labelField: 'name', trigger: 'row',highlight: true}"
                :data="tableData"
                @radio-change="currentChangeEvent"
            >
                <vxe-table-column type="radio" title width="60"></vxe-table-column>
                <vxe-table-column type="seq" width="60"></vxe-table-column>
                <vxe-table-column field="billId" title="单号"></vxe-table-column>
                <vxe-table-column field="orderNoCode" title="单据代码"></vxe-table-column>
                <vxe-table-column field="vochNum" title="总账凭证"></vxe-table-column>
                <vxe-table-column field="billDate" title="日期">
                    <template slot-scope="scope">{{scope.row.billDate|formatDate}}</template>
                </vxe-table-column>
                <vxe-table-column field="empName" title="人员"></vxe-table-column>
                <vxe-table-column field="deptName" title="部门"></vxe-table-column>
                <vxe-table-column title="明细">
                    <template slot-scope="scope">
                        <el-button type="text" @click="getById(scope.row)">查看</el-button>
                    </template>
                </vxe-table-column>
            </vxe-table>

            <vxe-pager
                background
                auto-hidden
                size="small"
                :loading="loading"
                :current-page="pagination.pageIndex"
                :page-size="pagination.pageSize"
                :total="pagination.pageTotal"
                :layouts="['PrevPage', 'JumpNumber','NextPage', 'Total']"
                @page-change="handlePageChange"
            ></vxe-pager>
        </div>

        <vxe-modal
            v-model="showDetails"
            title="明细列表"
            width="1200"
            height="400"
            :mask="false"
            :lock-view="false"
            resize
        >
            <vxe-table border auto-resize show-overflow highlight-hover-row :data="detailList">
                <vxe-table-column type="seq" width="60"></vxe-table-column>
                <vxe-table-column field="snNo" title="单据项次 "></vxe-table-column>
                <vxe-table-column field="accBankId" title="银行账号"></vxe-table-column>
                <vxe-table-column field="description" title="账号名称"></vxe-table-column>
                <vxe-table-column field="tranFlag" title="收支类型">
                    <template slot-scope="scope">{{scope.row.tranFlag == '1'?'收入':'支出'}}</template>
                </vxe-table-column>
                <vxe-table-column field="currId" title="币别"></vxe-table-column>
                <vxe-table-column field="amount" title="金额"></vxe-table-column>
                <vxe-table-column field="subId" title="科目"></vxe-table-column>
                <vxe-table-column field="adSubId" title="对方科目"></vxe-table-column>
                <vxe-table-column field="remark" title="摘要说明"></vxe-table-column>
                <vxe-table-column field="currRate" title="汇率"></vxe-table-column>
                <vxe-table-column field="lamount" title="本币金额"></vxe-table-column>
            </vxe-table>
        </vxe-modal>

        <!-- 人员搜索 -->
        <tree-search
            :isShow="showSearch"
            :dialogTitle="searchDialogTit"
            @edit="searchBack"
            @close="closeTreeDialog"
        ></tree-search>

        <table-search-singleset
            :isShow="showSearchSingle"
            :dialogTitle="searchDialogTitSingle"
            @edit="searchBackSingle"
            @close="closeTreeDialogSingle"
        ></table-search-singleset>
    </div>
</template>


<script>
import appMain from '../../../utils/app_main';
import _ from 'lodash';
import XEUtils from 'xe-utils';

export default {
    data() {
        return {
            pageTitle: '',
            containerHeight: '',
            tableData: [
                {
                    billDate: '1982-11-27T07:12:31.063Z', //日期
                    billId: 'nulla', //银行流水单号
                    companyId: 'minim', //账套id
                    deptId: 'adipisicing cillum ullamco', //部门id
                    deptName: 'sed sit ut sunt', //部门名称
                    empId: 'voluptate laborum', //人员id
                    empName: 'eu', //人员姓名
                    orderNoCode: 'eiusmod', //单别代码
                    orderNoId: 'nostrud occaecat laboris', //单别id
                    proName: 'dolore culpa sed minim ullamco', //项目名称
                    serial: 'aliqua labore', //主单序号,用于生成流水号
                    status: 'non magna', //状态:Y审核,N新建,X作废
                    tranId: 'commodo exe', //往来单位
                    tranName: 'culpa aliquip ad proident', //单位名称
                    vochNum: 'anim cupidatat' //总账凭证号
                },
                {
                    billDate: '1997-11-16T18:23:21.03Z',
                    billId: 'exercitation sint',
                    companyId: 'in ',
                    createTime: '2008-11-23T15:35:50.222Z',
                    createUserId: 'Excepteur',
                    createUserName: 'ad pariatur aliqua proident',
                    deptId: 'fugiat qui',
                    deptName: 'Lorem cillum labore occaecat',
                    domain: 'mollit est adipisicing labore aliqua',
                    empId: 'velit occaecat',
                    empName: 'Ut deserunt laboris',
                    isDel: 2137926,
                    orderNoCode: 'laborum consequat pariatur qui dolor',
                    orderNoId: 'aliqua',
                    proId: 'cupidatat dolor voluptate',
                    proName: 'occaecat',
                    serial: 'voluptate sunt dolor aliqua',
                    status: 'pariatur veniam',
                    tranId: 'commodo',
                    tranName: 'sit',
                    updateTime: '1998-01-15T13:11:00.019Z',
                    updateUserId: 'fugiat pariatur Lorem dolor',
                    updateUserName: 've',
                    vochNum: 'commodo'
                },
                {
                    billDate: '1982-07-18T00:14:04.969Z',
                    billId: 'minim nostrud ea qui dolore',
                    companyId: 'quis consectetur',
                    createTime: '2017-04-13T21:30:31.573Z',
                    createUserId: 'conse',
                    createUserName: 'ut fugiat ea Excepteur',
                    deptId: 'in eiusmod ut est deserunt',
                    deptName: 'aute non ullamco',
                    domain: 'ad',
                    empId: 'labore ut Lorem adipisicing do',
                    empName: 'adipisicing',
                    isDel: 70624022,
                    orderNoCode: 'Duis sint amet elit',
                    orderNoId: 'commodo proident',
                    proId: 'nisi mollit sunt occaecat',
                    proName: 'laboris ipsum dolore',
                    serial: 'velit sunt labore incididunt pariatur',
                    status: 'cillum aliqua irure consecte',
                    tranId: 'et in ea sit reprehenderit',
                    tranName: 'incididunt qui Lorem ipsum',
                    updateTime: '1967-11-08T03:21:44.072Z',
                    updateUserId: 'mollit magna non in et',
                    updateUserName: 'minim veniam occaecat non dolore',
                    vochNum: 'qui ex ut nulla'
                }
            ],
            //明细列表
            detailList: [
                {
                    accBankId: 'aliqua Duis sint incididunt id', //银行账号代码
                    description: 'aliqua Duis ', //银行账号名称
                    adSubId: 'irure ', //对方会计科目代码
                    amount: 47387130.864255, //原币金额
                    billId: 'culpa', //银行流水单号
                    currId: 'in ', //币别:默认 CNY
                    currRate: -33739873.99679619, //汇率
                    detailBillId: 'aliquip aliqua proident', //明细银行流水单号
                    lamount: -63712392.372452386, //本币金额
                    orderNoCode: 'veniam', //单别
                    orderNoId: 'ea dolore officia', //单别id
                    remark: 'in', //备注
                    snNo: 'sed do', //明细序号
                    subId: 'aute veniam', //会计科目代码
                    tranFlag: '1' //收支类型: 1 收入,-1支出
                }
            ],
            //新增明细列表
            billBankDetails: [],
            showDetails: false,
            checkTableRow: {},
            loading: false,
            searchDialogTit: '',
            showSearch: false,
            searchDialogTitSingle: '',
            showSearchSingle: false,
            pagination: {
                pageIndex: 1,
                pageSize: 10,
                pageTotal: 0
            },
            query: {
                billDate: '', //日期
                billId: '', //银行流水单号
                deptId: '', //部门id
                deptName: '', //部门名称
                empId: '', //人员id
                empName: '', //人员姓名
                orderNoCode: '', //单别代码
                orderNoId: '', //单别id
                orderRuleName: '', //单别
                vochNum: '' //总账凭证号
            },
            //会计期间
            orderNoList: [],
            rules: {
                empName: [{ required: true, message: '请选择', trigger: 'change' }],
                orderNoCode: [{ required: true, message: '请选择', trigger: 'change' }],
                billDate: [{ required: true, message: '请选择', trigger: 'change' }]
            },
            validRules: {
                snNo: [
                    { required: true, message: '项次必须填写' },
                    { pattern: '^[0-9]{1,18}$', message: '格式不正确,必须为数字' }
                ],
                amount: [{ required: true, message: '金额必须填写' }],
                adSubId: [{ required: true, message: '必须填写' }],
                accBankId: [{ required: true, message: '必须填写' }],
                remark: [{ min: 0, max: 250, message: '长度在 0 到 250 个字符' }]
            },

            tranFlagList: [
                {
                    label: '收入',
                    value: '1'
                },
                {
                    label: '支出',
                    value: '-1'
                }
            ],
            //新增,在编辑的明细行
            editRow: ''
        };
    },
    created() {
        this.getData();
    },
    mounted() {
        var div_height = window.screen.availHeight;
        var height = div_height - 100;
        this.containerHeight = height - 200;
        this.pageTitle = this.$router.currentRoute.meta.title;
        //$refs.xTree.setAllTreeExpand(true);
    },
    methods: {
        handlePageChange({ currentPage, pageSize }) {
            this.pagination.pageIndex = currentPage;
            this.pagination.pageSize = pageSize;
            this.getData();
        },

        //点击单选方法
        currentChangeEvent({ row }) {
            this.checkTableRow = row;
            console.log('currentChangeEvent', this.checkTableRow);
        },
        getData() {
            this.loading = true;
            console.log('getData', this.loading);
            let params = {
                pageNo: this.pagination.pageIndex,
                pageSize: this.pagination.pageSize,
                record: this.query
            };

            appMain
                .billBankDetailFindAllPage(params)
                .then(res => {
                    if (res.data.code === 20000) {
                        //TODO 测试环境使用
                        this.timer = setTimeout(() => {
                            //设置延迟执行
                            this.tableData = res.data.data.list;
                            this.pagination.pageSize = res.data.data.pageSize;
                            this.pagination.pageIndex = res.data.data.pageNum;
                            this.pagination.pageTotal = res.data.data.total;
                            this.loading = false;
                        }, 300);

                        console.log('getData tableData', this.tableData);
                    } else {
                        this.loading = false;
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    this.loading = false;
                    console.log(err);
                });
        },
        goAdd() {
            //this.dialogVisible = true;
            this.$router.push({
                path: '/bankTransaction'
            });
        },
        goEdit() {
            //this.$XModal.alert(this.checkTableRow.id);
            //this.$XModal.alert(JSON.stringify(this.$refs.xTree.getRadioRecord()));
            if (this.$refs.xTree.getRadioRecord() != null) {
                this.editForm = _.clone(this.$refs.xTree.getRadioRecord());

                this.$router.push({
                    path: '/bankTransaction',
                    query: {
                        id: this.editForm.billId
                    }
                });
                // this.getDetailById(this.editForm);
                // this.dialogVisibleEdit = true;
            } else {
                this.$message.info('请选择一条记录,再进行编辑');
            }
        },
        goBkpf() {
            if (this.$refs.xTree.getRadioRecord() != null) {
                this.editForm = _.clone(this.$refs.xTree.getRadioRecord());
                this.bkpf();
            } else {
                this.$message.info('请选择一条记录,再进行编辑');
            }
        },
        bkpf() {
            appMain
                .billBankbkpf(this.editForm.billId, this.editForm.orderNoId)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.getData();
                        this.$message.success(res.data.message);
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        delAllSelection() {
            if (this.$refs.xTree.getRadioRecord() != null) {
                this.editForm = _.clone(this.$refs.xTree.getRadioRecord());
            } else {
                this.$message.info('请选择一条记录,再进行编辑');
                return;
            }

            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    //请求接口删除数据
                    this.deleteRate();
                })
                .catch(() => {});
        },
        deleteRate() {
            appMain
                .billBankDetailDelById({}, this.editForm.billId)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.getData();
                        this.$message.success(res.data.message);
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },

        async addRate() {
            let updateRecords = this.$refs.xTable.tableData;
            const errMap = await this.$refs.xTable.validate(updateRecords).catch(errMap => errMap);
            if (errMap) {
                this.$message.warning('请按要求填写明细！');
                return;
            }
            let params = {
                billBankDetails: this.billBankDetails,
                billBankMaster: this.ruleForm
            };
            appMain
                .billBankDetailInsert(params)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.dialogVisible = false;
                        this.getData();
                        this.$message.success(res.data.message);
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        async updateRate() {
            let updateRecords = this.$refs.xTable.tableData;
            const errMap = await this.$refs.xTable.validate(updateRecords).catch(errMap => errMap);
            if (errMap) {
                this.$message.warning('请按要求填写明细！');
                return;
            }
            let params = {
                billBankDetails: this.billBankDetails,
                billBankMaster: this.editForm
            };
            appMain
                .billBankDetailUpdateById(params)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.dialogVisibleEdit = false;
                        this.getData();
                        this.$message.success(res.data.message);
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        getById(row) {
            this.showDetails = true;
            appMain
                .billBankDetailFindById({}, row.billId)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.detailList = res.data.data.billBankDetails;
                        this.showDetails = true;
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        getDetailById(row) {
            appMain
                .billBankDetailFindById({}, row.billId)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.billBankDetails = res.data.data.billBankDetails;
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        getOrderNoList() {
            appMain
                .orderNoRuleFindAll()
                .then(res => {
                    if (res.data.code === 20000) {
                        this.orderNoList = res.data.data;
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        orderNoChage(val) {
            console.log('orderNoChage', val);
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => {
                    this.dialogVisible = false;
                    done();
                })
                .catch(_ => {});
        },
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    if (formName == 'searchRuleForm') {
                        //新增科目
                        this.getData();
                    } else if (formName == 'ruleForm') {
                        this.addRate();
                    } else if (formName == 'editForm') {
                        this.updateRate();
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.query = {
                billDate: '', //日期
                billId: '', //银行流水单号
                deptId: '', //部门id
                deptName: '', //部门名称
                empId: '', //人员id
                empName: '', //人员姓名
                orderNoCode: '', //单别代码
                orderNoId: '', //单别id
                orderRuleName: '', //单别
                vochNum: '' //总账凭证号
            };
        },
        // 选择姓名
        showTreeDialog(tit) {
            console.log('showTreeDialog');
            this.searchDialogTit = tit;
            this.showSearch = true;
        },
        // 树组件搜索结果返回
        searchBack(data) {
            console.log(data.backData, 'searchTreeBack');
            this.query.empName = data.backData.name;
            this.query.empId = data.backData.id;
            this.query.deptName = data.backData.organizationName;
            this.query.deptId = data.backData.organizationId;
            this.showSearch = false;
        },
        closeTreeDialog(data) {
            this.showSearch = data.showDialog;
        },
        showTreeDialog1(tit) {
            console.log('showTreeDialog1');
            this.searchDialogTit1 = tit;
            this.showSearch1 = true;
        },

        showTreeDialogSingle(tit) {
            console.log('showTreeDialogSingle');
            this.searchDialogTitSingle = tit;
            this.showSearchSingle = true;
        },
        // 单别树组件搜索结果返回
        searchBackSingle(data) {
            console.log(data.backData, 'searchTreeBackSingle');
            this.query.orderNoId = data.backData.id;
            this.query.orderNoCode = data.backData.ruleCode;
            this.query.orderRuleName = data.backData.ruleName;
            this.showSearchSingle = false;
        },
        closeTreeDialogSingle(data) {
            this.showSearchSingle = data.showDialog;
        },
        countAmount(obj) {
            console.log('countAmount', obj.row);
            let mount = XEUtils.multiply(obj.row.amount, obj.row.currRate);
            console.log('countAmount mount', mount);
            this.billBankDetails[obj.rowIndex].lamount = mount;
        }
    },
    computed: {},
    watch: {},
    filters: {
        //时间过滤器
        formatDate: function(val) {
            let date = new Date(val);
            return appMain.formatDate(date, 'yyyy-MM-dd hh:mm:ss');
        }
    }
};
</script>

<style lang="css" scoped>
.el-card {
    height: 100%;
}

.flex-right {
    padding: 20px;
}

.handler-box {
    border: 1px solid rgb(232, 234, 236);
    padding: 5px;
    margin-bottom: 15px;
}

.tree-box .flex-left {
    padding: 0px !important;
}

.el-date-editor {
    width: 100%;
}

.vxe-select--panel {
    z-index: 9997 !important;
}
.vxe-input--panel.type--date,
.vxe-input--panel.type--month,
.vxe-input--panel.type--week,
.vxe-input--panel.type--year {
    z-index: 9998 !important;
}

.vxe-table--tooltip-wrapper,
.theme--dark,
.placement--top,
.is--visible,
.vxe-table--valid-error {
    z-index: 9998 !important;
}

.vxe-table--ignore-clear,
.vxe-select--panel,
.is--transfer {
    z-index: 9998 !important;
}
.vxe-select-option--wrapper,
.vxe-select-option {
    z-index: 9998 !important;
}

body > .vxe-select--panel {
    z-index: 9998 !important;
}
</style>